<template>
  <view class="container">
    <view class="address-list">
      <!-- 使用 uni-swipe-action 组件实现左滑删除 -->
      <uni-swipe-action>
        <uni-swipe-action-item
          v-for="item in addressList"
          :key="item.id"
          :right-options="swipeOptions"
          @click="handleSwipeClick($event, item)"
        >
          <view class="address-item" @tap="selectAddress(item)">
            <view class="radio" v-if="isSelect">
              <radio
                :checked="item.id === selectedId"
                :value="item.id"
                color="#ff4444"
              />
            </view>

            <view class="info">
              <view class="user">
                <text class="name">{{ item.receiverName }}</text>
                <text class="phone">{{ item.phoneNumber }}</text>
                <text class="tag" v-if="item.isDefault">默认</text>
              </view>
              <view class="address"
                >{{ item.province }}{{ item.city }}{{ item.district
                }}{{ item.detailAddress }}</view
              >
            </view>
            <view class="edit-btn" @tap.stop="editAddress(item)">
              <uni-icons type="compose" size="20" color="#666"></uni-icons>
            </view>
          </view>
        </uni-swipe-action-item>
      </uni-swipe-action>

      <!-- 空状态 -->
      <view class="empty" v-if="addressList.length === 0">
        <image src="/static/empty-address.png" mode="aspectFit" />
        <text>暂无收货地址</text>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="footer">
      <view class="btn-group">
        <button class="wechat-btn" @tap="getWechatAddress" v-if="isWechat">
          从微信获取
        </button>
        <button class="add-btn" @tap="addAddress">新增收货地址</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";

// 导入地址服务
import addressService from "@/services/address";

// 响应式数据
const addressList = ref([]);
const isSelect = ref(false);
const isWechat = ref(false);

// 左滑操作按钮配置
const swipeOptions = [
  {
    text: "删除",
    style: {
      backgroundColor: "#ff4444",
    },
  },
];

// 添加选中项的 ID
const selectedId = ref("");

// 处理左滑按钮点击
const handleSwipeClick = (e, item) => {
  if (e.index === 0) {
    // 删除操作
    uni.showModal({
      title: "提示",
      content: "确定要删除这个地址吗？",
      success: async (res) => {
        if (res.confirm) {
          await deleteAddress(item.id);
        }
      },
    });
  }
};

// 检查是否是微信小程序环境
const checkPlatform = () => {
  // #ifdef MP-WEIXIN
  isWechat.value = true;
  // #endif
};

// 获取地址列表的方法需要修改
const getAddressList = async () => {
  try {
    const res = await addressService.getList();
    addressList.value = res.data;
  } catch (error) {
    uni.showToast({
      title: "获取地址列表失败",
      icon: "none",
    });
    console.error("获取地址列表失败:", error);
  }
};

// 选择地址
const selectAddress = (address) => {
  if (!isSelect.value) return;

  selectedId.value = address.id;

  // 返回上一页并传递选中的地址
  const pages = getCurrentPages();
  const prevPage = pages[pages.length - 2];

  if (prevPage?.$vm?.updateAddress) {
    prevPage.$vm.updateAddress(address);
    uni.navigateBack();
  }
};

// 编辑地址
const editAddress = (address) => {
  uni.navigateTo({
    url: `/pages/address/edit?id=${address.id}`,
  });
};

// 新增地址
const addAddress = () => {
  uni.navigateTo({
    url: "/pages/address/edit",
  });
};

// 删除地址的方法（需要新增）
const deleteAddress = async (id) => {
  try {
    await addressService.remove(id);
    uni.showToast({
      title: "删除成功",
      icon: "success",
    });
    // 重新获取地址列表
    getAddressList();
  } catch (error) {
    uni.showToast({
      title: "删除失败",
      icon: "none",
    });
  }
};

// 设置默认地址的方法（需要新增）
const setDefaultAddress = async (id) => {
  try {
    await addressService.setDefault(id);
    uni.showToast({
      title: "设置成功",
      icon: "success",
    });
    // 重新获取地址列表
    getAddressList();
  } catch (error) {
    uni.showToast({
      title: "设置失败",
      icon: "none",
    });
  }
};

// 从微信获取收货地址
const getWechatAddress = () => {
  uni.chooseAddress({
    success: async (res) => {
      // 将微信���址信息转换为我们的地址格式
      const addressData = {
        receiverName: res.userName,
        phoneNumber: res.telNumber,
        province: res.provinceName,
        city: res.cityName,
        district: res.countyName,
        detailAddress: res.detailInfo,
        isDefault: false,
      };

      try {
        await addressService.add(addressData);
        uni.showToast({
          title: "添加成功",
          icon: "success",
        });
        // 刷新地址列表
        getAddressList();
      } catch (error) {
        uni.showToast({
          title: "添加失败",
          icon: "none",
        });
      }
    },
    fail: (err) => {
      if (err.errMsg.indexOf("auth deny") !== -1) {
        uni.showToast({
          title: "请授权通讯地址",
          icon: "none",
        });
      }
    },
  });
};

// 生命周期
onLoad((options) => {
  isSelect.value = options.select === "1" || options.select === 1;
  checkPlatform();
});

onMounted(() => {
  getAddressList();
});
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
}

.address-list {
  padding: 20rpx;

  .address-item {
    display: flex;
    align-items: center;
    background-color: #fff;
    padding: 30rpx 20rpx;

    .radio {
      margin-right: 20rpx;
      display: flex;
      align-items: center;
    }

    .info {
      flex: 1;
      margin-right: 20rpx;

      .user {
        margin-bottom: 10rpx;

        .name {
          font-size: 28rpx;
          color: #333;
          margin-right: 20rpx;
        }

        .phone {
          font-size: 28rpx;
          color: #666;
        }

        .tag {
          font-size: 20rpx;
          color: #ff4444;
          border: 2rpx solid #ff4444;
          padding: 2rpx 10rpx;
          border-radius: 20rpx;
          margin-left: 20rpx;
        }
      }

      .address {
        font-size: 26rpx;
        color: #666;
        line-height: 1.4;
      }
    }

    .edit-btn {
      padding: 10rpx;
    }
  }

  .empty {
    padding: 100rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;

    image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 20rpx;
    }

    text {
      font-size: 28rpx;
      color: #999;
    }
  }
}

.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx;
  background-color: #fff;

  .btn-group {
    display: flex;
    gap: 20rpx;

    .wechat-btn {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      background-color: #07c160;
      color: #fff;
      font-size: 28rpx;
      border-radius: 40rpx;
    }

    .add-btn {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      background-color: #ff4444;
      color: #fff;
      font-size: 28rpx;
      border-radius: 40rpx;
    }
  }
}
</style>
